package com.wolfcode.web.controller.minIo.controller;

import com.wolfcode.common.core.domain.AjaxResult;
import com.wolfcode.common.utils.StringUtils;
import com.wolfcode.common.utils.file.FileUploadUtils;
import com.wolfcode.common.utils.uuid.IdUtils;
import com.wolfcode.contract.domain.info.ContractInfo;
import com.wolfcode.contract.service.IContractService;
import com.wolfcode.web.controller.minIo.config.MinIoConfig;
import io.minio.*;
import io.minio.errors.*;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;

@Controller
public class MinIoController {

    @Resource
    private MinioClient minioClient;
    @Autowired
    private IContractService contractService;

    /**
     * MinIO上传请求
     */
    @PostMapping("/common/minio/upload")
    @ResponseBody
    public AjaxResult minIoUploadFile(ContractInfo contractInfo) throws Exception {
        Assert.notNull(contractInfo,"参数异常");
        MultipartFile file = contractInfo.getFile();
        Assert.notNull(file,"未提交文件");
        String fileName = upload(file);
        HashMap<String,Object> map = new HashMap<>();
        map.put("fileName",fileName);
        map.put("contractInfo",contractInfo);
        contractService.insertContract(map);
        return AjaxResult.success("上传成功!", fileName);
    }


    @NotNull
    private String upload(MultipartFile file) throws IOException, ErrorResponseException, InsufficientDataException, InternalException, InvalidKeyException, InvalidResponseException, NoSuchAlgorithmException, ServerException, XmlParserException {
        // 自己生成唯一的文件名
        String fileName = IdUtils.fastSimpleUUID() + System.currentTimeMillis();
        // 获取文件后缀
        String extension = FileUploadUtils.getExtension(file);
        InputStream inputStream = file.getInputStream();

        if (StringUtils.isNotEmpty(extension)) {
            fileName = fileName.concat(".").concat(extension);
        }

        // 使用步骤：
        // 1：创建minio客户端连接对象
        // 2: 检查存储空间是否存在, 存储空间不存在上传不了
        boolean exists = minioClient.bucketExists(BucketExistsArgs.builder()
                .bucket(MinIoConfig.getBucketInfo()).build());
        if (!exists) {
            throw new RuntimeException("存储空间不存在!");
        }

        PutObjectArgs objectArgs = PutObjectArgs.builder()
                .bucket(MinIoConfig.getBucketInfo())
                .object(fileName)
                .stream(inputStream, inputStream.available(), -1)
                .build();

        // 3:上传文件
        minioClient.putObject(objectArgs);
        //4：拼接图片访问连接
//        return MinIoConfig.getEndpoint() + "/" + MinIoConfig.getBucket() + "/" + fileName;
        return fileName;
    }


}
